package com.studyweb.mapper;

import com.alibaba.fastjson2.JSON;
import com.studyweb.pojo.entity.PaperResult;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface PaperResultMapper {
    
    /**
     * 插入试卷测验结果
     */
    @Insert("INSERT INTO paper_result(user_id, paper_id, score, total_score, correct_count, " +
            "wrong_count, unanswered_count, time_spent, start_time, end_time, create_time, user_answers, " +
            "scoring_method, scoring_description) " +
            "VALUES(#{userId}, #{paperId}, #{score}, #{totalScore}, #{correctCount}, " +
            "#{wrongCount}, #{unansweredCount}, #{timeSpent}, #{startTime}, #{endTime}, #{createTime}, " +
            "#{userAnswers, typeHandler=com.studyweb.mapper.JsonTypeHandler}, " +
            "#{scoringMethod}, #{scoringDescription})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(PaperResult paperResult);
    
    /**
     * 根据ID查询试卷测验结果
     */
    @Select("SELECT * FROM paper_result WHERE id = #{id}")
    @Results({
        @Result(property = "userAnswers", column = "user_answers", typeHandler = com.studyweb.mapper.JsonTypeHandler.class)
    })
    PaperResult selectById(Long id);
    
    /**
     * 根据用户ID和试卷ID查询试卷测验结果
     */
    @Select("SELECT * FROM paper_result WHERE user_id = #{userId} AND paper_id = #{paperId} ORDER BY create_time DESC")
    @Results({
        @Result(property = "userAnswers", column = "user_answers", typeHandler = com.studyweb.mapper.JsonTypeHandler.class)
    })
    List<PaperResult> selectByUserIdAndPaperId(@Param("userId") Long userId, @Param("paperId") Long paperId);
    
    /**
     * 根据用户ID查询试卷测验结果
     */
    @Select("SELECT * FROM paper_result WHERE user_id = #{userId} ORDER BY create_time DESC")
    @Results({
        @Result(property = "userAnswers", column = "user_answers", typeHandler = com.studyweb.mapper.JsonTypeHandler.class)
    })
    List<PaperResult> selectByUserId(Long userId);
    
    /**
     * 更新试卷测验结果
     */
    @Update("UPDATE paper_result SET score = #{score}, total_score = #{totalScore}, " +
            "correct_count = #{correctCount}, wrong_count = #{wrongCount}, " +
            "unanswered_count = #{unansweredCount}, time_spent = #{timeSpent}, " +
            "start_time = #{startTime}, end_time = #{endTime}, " +
            "user_answers = #{userAnswers, typeHandler=com.studyweb.mapper.JsonTypeHandler}, " +
            "scoring_method = #{scoringMethod}, scoring_description = #{scoringDescription} " +
            "WHERE id = #{id}")
    void update(PaperResult paperResult);
    
    /**
     * 删除试卷测验结果
     */
    @Delete("DELETE FROM paper_result WHERE id = #{id}")
    void deleteById(Long id);
}